import { _decorator, assetManager, Button, Camera, Canvas, Component, error, find, ImageAsset, instantiate, Label, Material, Node, Prefab, resources, Sprite, SpriteAtlas, SpriteFrame, sys, TextAsset, Texture2D, tween, Vec3 } from 'cc';
import { EventMgr, IEMsg } from './EventMgr';
import { AudioMgr } from './AudioMgr';
import { AbNames } from '../../../Game/Scripts/Config/ResConfig';
import { ResManager } from './ResManager';
import { GameUtils } from '../Utils/GameUtils';
const { ccclass, property } = _decorator;

export interface ICloseView {
    abName: string,
    path: string,
}

// @ccclass('UIComponent')
export class UIComponent extends Component {
    //关闭时候打开的界面
    public closeView: ICloseView = {
        abName: null,
        path: null
    };

    //自定义消息的keys
    public eventMsgs: IEMsg[] = [];

    protected onDestroy(): void {
        this._UnRegisterEvent();
    }

    // 注册事件
    public RegisterEvent(EventName: string, callback,caller): void{
        var item: IEMsg  ={
            msgName: EventName,
            callback: callback,
            caller: caller
        } 
        this.eventMsgs.push(item);
        // console.log('=====RegisterEvent====',this.eventMsgs,this.node.name);
        EventMgr.inst.AddEventListener(item.msgName,item.callback,item.caller);
    }

    // 销毁事件
    public _UnRegisterEvent(): void{
        // console.log('=====_UnRegisterEvent====',this.eventMsgs,this.node.name);
        for (let i = 0; i < this.eventMsgs.length; i++) {
            const element:IEMsg = this.eventMsgs[i];
            EventMgr.inst.RemoveEventListener(element.msgName,element.callback,element.caller);
        }
    }

    /**
     * 
     * @param viewName 路径 如：a/b/c
     * @returns 
     */
    public ViewNode(viewName:string): Node {
        var node = this.node.getChildByPath(viewName);
        return node;
    }

    /**
     * 
     * @param viewName 路径 如：a/b/c
     * @param classConstructor 组件名
     * @returns 
     */
    public ViewComponent<T extends Component>(viewName: string, classConstructor): T {
        var node = this.node.getChildByPath(viewName);
        if(node === null) {
            return null;
        }

        var com = node.getComponent(classConstructor);
        return com as T;
    } 

    // 编写一些接口，方便我们对UI组件做监听;
    public AddButtonListener(viewName: string, caller: any, func: any) {
        var view_node = this.ViewNode(viewName);
        if (!view_node) {
            return;
        }
        var btn = view_node.getComponent(Button);
        if(!btn){
            btn = view_node.addComponent(Button);
            btn.transition = Button.Transition.SCALE;
        }

        view_node.on("click",(btn: Button)=>{
            func.call(caller,btn)
            AudioMgr.inst.playOneShot();
        } , caller);
    }

    //添加窗口打开动画
    public AddOpenAni(root: Node): void {
        tween()
            .target(root)
            .hide()
            .to(0, { scale: new Vec3(0, 0, 0) })
            .show()
            .to(0.1, { scale: new Vec3(1, 1, 1), easing: 'quintOutIn' })
            .start()
    }

    public OnBtnCloseClick(): void{
        this.node.destroy();
    }
    // end

    /**
     * 加载url图片
     * @param url 
     */
    public async LoadRemoteImage(remoteUrl: string, sp: Sprite) {
        // console.log('============LoadRemoteImage=========',remoteUrl.indexOf('.jpeg'))
        if(!remoteUrl){
            return;
        }

        let platform = sys.platform;
        if(platform === sys.Platform.MOBILE_BROWSER || sys.Platform.DESKTOP_BROWSER){ //网页平台图片无发直接读取，会出现跨域文体，现在直接把图盘放到本地
            // let url = "head1";
           let url = remoteUrl.slice(-9).split('.')[0];
           url = (url === 'ead10') ? 'head10' : url;
            // console.log('==========LoadRemoteImage========',url);
            let sf = ResManager.inst.getAsset(AbNames.Common,`Guis/imgs/${url}/spriteFrame`,SpriteFrame) as SpriteFrame;
            if(sf){
                sp.spriteFrame = sf;
            }
        }else{

            if (remoteUrl.indexOf('.png') !== -1 || remoteUrl.indexOf('.jpg') !== -1 || remoteUrl.indexOf('.jpeg') !== -1) {
                let type = '.png';
                if(remoteUrl.indexOf('.jpg') !== -1){
                    type = '.jpg';
                }else if(remoteUrl.indexOf('.jpeg') !== -1){
                    type = '.jpeg';
                }
                // console.log('======加载有后缀的图片========',type)
                assetManager.loadRemote<ImageAsset>(remoteUrl,  { ext: type },function (err, imageAsset) {
                    if (err) {
                        console.log('========loadTexture1 reject==========')
                        return;
                    }else{
                        const texture = new Texture2D();
                        texture.image = imageAsset;
                        const spriteFrame = new SpriteFrame();
                        spriteFrame.texture = texture;
                        console.log('========LoadRemoteImage1112==========',sp,spriteFrame)
                        sp.spriteFrame = spriteFrame;
                    }
                });
                // const texture = await this.loadTexture1(remoteUrl,type);
                // console.log('=======loadTexture=texture1==========',texture)
                // if (texture) {
                //     const spriteFrame = new SpriteFrame();
                //     spriteFrame.texture = texture;
                //     sp.spriteFrame = spriteFrame;
                // }
            } else {
                const texture = await this.loadTexture(remoteUrl);
                console.log('=======loadTexture=texture==========',texture,remoteUrl)
                if (texture) {
                    const spriteFrame = new SpriteFrame();
                    spriteFrame.texture = texture;
                    console.log('========LoadRemoteImage1111==========',sp,spriteFrame)
                    sp.spriteFrame = spriteFrame;
                }
            }
        }
    }

     //有后缀的图片
    private loadTexture1(remoteUrl: string,type:string): Promise<Texture2D | null> {
        return new Promise((resolve, reject) => {
            assetManager.loadRemote<ImageAsset>(remoteUrl,  { ext: type },function (err, imageAsset) {
                if (err) {
                    console.log('========loadTexture1 resolve==========')
                    reject(null);
                }else{
                    const texture = new Texture2D();
                    texture.image = imageAsset;
                    resolve(texture);
                }
            })
        });
    }

    //没有后缀的图片
    private loadTexture(remoteUrl: string): Promise<Texture2D | null> {
        return new Promise((resolve, reject) => {
            assetManager.loadRemote<ImageAsset>(remoteUrl, {ext: '.png'}, function (err, imageAsset) {
                if (err) {
                    console.log('========loadTexture reject==========')
                    reject(null);
                }else{
                    const texture = new Texture2D();
                    texture.image = imageAsset;
                    resolve(texture);
                }
            });
        });
    }

    //设置文字的渐变
    public setLabGrad(node:Node,texture:Texture2D){
        let label = node.getComponent(Label);
        let mat: Material = label.customMaterial;

        mat.setProperty('gradTexture',texture);

            // 等待纹理加载完成
            // texture.addEventListener('load', () => {
            //     // 获取材质的第一个纹理属性（通常是 albedoTexture）
            //     const textureProperty:any = mat.getProperty('gradTexture');
            //     console.log('=====setLabGrad==========',textureProperty)

            //     // 设置新的纹理
            //     textureProperty.setValue(texture);
            // });

       
        // 设置新的纹理
        // textureProperty.setValue(texture);
    }

    // 设置背景动画
    public setBgAni(idx: number = 1){
        let pre = ResManager.inst.getAsset(AbNames.Common,'Prefabs/BgAni',Prefab) as Prefab;
        let item = instantiate(pre);
        item.parent = this.node;
        item.setSiblingIndex(idx);
    }

    /**
     * 
     * @param sp 
     * @param type 0是圆的图 1 是方形带圆角
     */
    public setHeadMat(sp: Sprite, type: number = 0){
        let mat = null;
        if(type === 0){
            mat = ResManager.inst.getAsset(AbNames.Common,'Mats/mask3/mask3',Material) as Material;
        }else if(type === 1){
            mat = ResManager.inst.getAsset(AbNames.Common,'Mats/mask1/mask1',Material) as Material;
        }
        if(sp && mat){
            sp.customMaterial = mat;
        }else{
            console.log('======setHeadMat errot========',sp,mat);
        }
    }

    /**
     * 对象里面是否存在某个属性
     * @param obj 
     * @param key 
     * @returns 
     */
    public hasProInObj(obj:Object, key:string): Boolean{
        let res = false;
        res = obj.hasOwnProperty(key);
        return res;
    }
}
